<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">清泉到家系统</h3>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-type-switch">
        <div 
          class="switch-item" 
          :class="{ active: loginType === 'password' }" 
          @click="loginType = 'password'"
        >
          账号密码登录
        </div>
        <div 
          class="switch-item" 
          :class="{ active: loginType === 'email' }" 
          @click="loginType = 'email'"
        >
          邮箱验证码登录
        </div>
      </div>

      <!-- 账号密码登录 -->
      <template v-if="loginType === 'password'">
        <el-form-item prop="username">
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="用户名"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
            prefix-icon="el-icon-user"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            prefix-icon="el-icon-lock"
            @keyup.enter.native="handleLogin"
          />
        </el-form-item>
      </template>

      <!-- 邮箱验证码登录 -->
      <template v-else>
        <el-form-item prop="email">
          <el-input
            ref="email"
            v-model="emailLoginForm.email"
            placeholder="请输入QQ邮箱"
            name="email"
            type="email"
            tabindex="1"
            autocomplete="on"
            prefix-icon="el-icon-message"
          />
        </el-form-item>

        <el-form-item prop="code">
          <div class="verification-code">
            <el-input
              ref="code"
              v-model="emailLoginForm.code"
              placeholder="验证码"
              name="code"
              type="text"
              tabindex="2"
              autocomplete="on"
              prefix-icon="el-icon-key"
              class="code-input"
              @keyup.enter.native="handleEmailLogin"
            />
            <el-button 
              type="primary" 
              class="code-button" 
              :disabled="codeSending || cooldown > 0"
              @click="sendCode"
            >
              {{ cooldown > 0 ? `${cooldown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </template>

      <el-form-item prop="role">
        <el-select v-model="loginForm.role" placeholder="请选择角色" style="width: 100%">
          <el-option label="客户" value="USER"></el-option>
          <el-option label="管理员" value="ADMIN"></el-option>
          <el-option label="送水员" value="DELIVERY"></el-option>
        </el-select>
      </el-form-item>

      <el-button 
        :loading="loading" 
        type="primary" 
        style="width:100%;margin-bottom:30px;" 
        @click.native.prevent="loginType === 'password' ? handleLogin() : handleEmailLogin()"
      >
        登录
      </el-button>

      <div class="register-link">
        <router-link to="/register">
          <span>没有账号？立即注册</span>
        </router-link>
      </div>
    </el-form>
  </div>
</template>

<script>
import { login, emailLogin, sendVerificationCode } from '@/api/auth'
import { validUsername, validPassword, validEmail } from '@/utils/validate'
import { asyncRoutes } from '@/router'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('密码不能少于6个字符'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback()
      } else {
        callback()
      }
    }
    return {
      loginType: 'password', // 默认使用密码登录
      loginForm: {
        username: '',
        password: '',
        role: 'USER' // 默认选择客户角色
      },
      emailLoginForm: {
        email: '',
        code: '',
        role: 'USER' // 默认选择客户角色
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        email: [{ required: true, trigger: 'blur', validator: validateEmail }],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }]
      },
      passwordType: 'password',
      loading: false,
      redirect: undefined,
      codeSending: false,
      cooldown: 0,
      timer: null
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    'loginForm.role': function(newVal) {
      // 同步两个表单的角色
      this.emailLoginForm.role = newVal;
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 添加动态路由
    addDynamicRoutes(role) {
      // 将后端角色映射到前端路由角色
      const roleMap = {
        'USER': 'customer',
        'ADMIN': 'admin',
        'DELIVERY': 'delivery'
      }
      const mappedRole = roleMap[role] || 'customer'
      
      // 根据角色过滤路由
      const accessRoutes = this.filterAsyncRoutes(asyncRoutes, mappedRole)
      
      // 动态添加路由
      accessRoutes.forEach(route => {
        this.$router.addRoute(route)
      })
      
      // 添加404路由
      this.$router.addRoute({ path: '*', redirect: '/404', hidden: true })
      
      return mappedRole
    },
    
    // 根据角色过滤路由
    filterAsyncRoutes(routes, role) {
      const res = []
      
      routes.forEach(route => {
        const tmp = { ...route }
        if (this.hasPermission(tmp, role)) {
          if (tmp.children) {
            tmp.children = this.filterAsyncRoutes(tmp.children, role)
          }
          res.push(tmp)
        }
      })
      
      return res
    },
    
    // 判断是否有权限
    hasPermission(route, role) {
      if (route.meta && route.meta.roles) {
        return route.meta.roles.includes(role)
      } else {
        return true
      }
    },
    
    // 账号密码登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          login(this.loginForm).then(response => {
            // 登录成功，保存token和用户信息
            localStorage.setItem('token', response.data.token)
            localStorage.setItem('userRole', response.data.role)
            localStorage.setItem('username', response.data.username)
            localStorage.setItem('userId', response.data.id)
            
            try {
              // 先添加路由
              const mappedRole = this.addDynamicRoutes(response.data.role)
              
              // 根据角色决定跳转路径
              let redirectPath = '/'
              if (mappedRole === 'customer') {
                redirectPath = '/customer/products'
              } else if (mappedRole === 'admin') {
                redirectPath = '/admin/dashboard'
              } else if (mappedRole === 'delivery') {
                redirectPath = '/delivery/orders'
              }
              
              // 使用push而不是replace，并使用setTimeout确保路由添加完成
              setTimeout(() => {
                this.$router.push(redirectPath).catch(err => {
                  console.error('路由跳转错误:', err)
                  this.$router.push('/')
                })
                this.loading = false
              }, 300)
            } catch (error) {
              console.error('路由添加错误:', error)
              this.$router.push('/')
              this.loading = false
            }
          }).catch(error => {
            // 登录失败，错误消息已由全局拦截器处理
            console.error('登录失败:', error)
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    
    // 邮箱验证码登录
    handleEmailLogin() {
      // 验证邮箱和验证码
      if (!this.emailLoginForm.email) {
        this.$message.error('请输入邮箱');
        return;
      }
      if (!this.emailLoginForm.code) {
        this.$message.error('请输入验证码');
        return;
      }
      
      this.loading = true;
      emailLogin({
        email: this.emailLoginForm.email,
        code: this.emailLoginForm.code,
        role: this.loginForm.role // 使用选择的角色
      }).then(response => {
        // 登录成功，保存token和用户信息
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('userRole', response.data.role)
        localStorage.setItem('username', response.data.username)
        localStorage.setItem('userId', response.data.userId)
        
        try {
          // 先添加路由
          const mappedRole = this.addDynamicRoutes(response.data.role)
          
          // 根据角色决定跳转路径
          let redirectPath = '/'
          if (mappedRole === 'customer') {
            redirectPath = '/customer/products'
          } else if (mappedRole === 'admin') {
            redirectPath = '/admin/dashboard'
          } else if (mappedRole === 'delivery') {
            redirectPath = '/delivery/orders'
          }
          
          // 使用push而不是replace，并使用setTimeout确保路由添加完成
          setTimeout(() => {
            this.$router.push(redirectPath).catch(err => {
              console.error('路由跳转错误:', err)
              this.$router.push('/')
            })
            this.loading = false
          }, 300)
        } catch (error) {
          console.error('路由添加错误:', error)
          this.$router.push('/')
          this.loading = false
        }
      }).catch(error => {
        // 登录失败，错误消息已由全局拦截器处理
        console.error('邮箱登录失败:', error)
        this.loading = false
      })
    },
    
    // 发送验证码
    sendCode() {
      // 检查邮箱是否填写
      if (!this.emailLoginForm.email) {
        this.$message.error('请先填写QQ邮箱');
        return;
      }
      
      // 检查邮箱格式
      if (!validEmail(this.emailLoginForm.email)) {
        this.$message.error('请输入正确的QQ邮箱格式');
        return;
      }
      
      this.codeSending = true;
      
      // 调用发送验证码接口
      sendVerificationCode({
        email: this.emailLoginForm.email
      }).then(response => {
        this.$message.success('验证码已发送，请查收邮件');
        this.startCooldown(); // 开始倒计时
      }).catch(error => {
        console.error('发送验证码失败:', error);
        // 错误消息已由全局拦截器处理
      }).finally(() => {
        this.codeSending = false;
      });
    },
    
    // 倒计时
    startCooldown() {
      this.cooldown = 60; // 60秒倒计时
      this.timer = setInterval(() => {
        if (this.cooldown > 0) {
          this.cooldown--;
        } else {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    }
  }
}
</script>

<style lang="scss" scoped>
$bg: #283443;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
  
  .title-container {
    position: relative;
    
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  
  .register-link {
    text-align: center;
    font-size: 14px;
    color: $light_gray;
    
    span {
      color: #409EFF;
      cursor: pointer;
    }
  }
  
  .verification-code {
    display: flex;
    
    .code-input {
      flex: 1;
    }
    
    .code-button {
      margin-left: 10px;
      width: 120px;
    }
  }
  
  /* 标签页样式 */
  .login-type-switch {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    
    .switch-item {
      padding: 10px 20px;
      cursor: pointer;
      color: #909399;
      font-size: 16px;
      margin: 0 10px;
      position: relative;
      
      &.active {
        color: #409EFF;
        font-weight: bold;
        
        &:after {
          content: '';
          position: absolute;
          bottom: -1px;
          left: 0;
          right: 0;
          height: 2px;
          background-color: #409EFF;
        }
      }
      
      &:hover {
        color: #409EFF;
      }
    }
  }
}
</style>

<style lang="scss">
/* 全局样式覆盖 */
.login-container {
  .el-select .el-input {
    width: 100%;
  }
}
</style> 